<template>
    <div>
        <el-dialog
                v-dialogDrag :visible.sync="chartDivDialogVisible.v"
                width="65%"
                title="添加图表">
            <div class="content" v-loading="isLoad">
                <el-col :span="8">
                    <div>
                        <p>选择数据：</p>
                        <el-select style="width:90%;"
                                   v-model="value" clearable placeholder="请选择添加数据"
                                   @change="changeDataFields">
                            <el-option
                                    v-for="item in options"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.label">
                            </el-option>
                        </el-select>
                    </div>
                    <div>
                        <p style="margin-top: 20px">选择X轴：</p>
                        <el-select style="width:90%;"
                                   v-model="xfield" clearable :disabled="this.canSelected" placeholder="请选择X轴">
                            <el-option
                                    v-for="item in fieldOption"
                                    :key="item.field"
                                    :label="item.fieldName"
                                    :value="item.field">
                            </el-option>
                        </el-select>
                    </div>
                    <div>
                        <p style="margin-top: 20px">选择Y轴：</p>
                        <el-select style="width:90%;"
                                   v-model="yfield" clearable :disabled="this.canSelected" placeholder="请选择Y轴">
                            <el-option
                                    v-for="item in fieldOption"
                                    :key="item.field"
                                    :label="item.fieldName"
                                    :value="item.field">
                            </el-option>
                        </el-select>
                    </div>
                    <div class="block">
                        <p style="margin-top: 20px">时间范围：</p>
                        <el-date-picker
                                :disabled="this.isSelected"
                                v-model="time"
                                style="width:90%;"
                                type="datetimerange"
                                range-separator="至"
                                start-placeholder="开始日期"
                                end-placeholder="结束日期">
                        </el-date-picker>
                    </div>
                    <div>
                        <p style="margin-top: 20px">空间范围：</p>
                        <el-input v-model="paramsFormData"
                                  style="width:90%;"
                                  :disabled="this.isSelected"
                                  clearable placeholder="请输入空间范围">
                        </el-input>
                        <span style="margin-left: 5px;">
                            <a @click="openPosition" id="icon">
                              <n3-icon type="map-marker" size="large"></n3-icon>
                            </a>
                        </span>
                    </div>
                    <el-button @click="load" type="primary" plain style="height:40px;width:35%;margin-top: 40px;">
                        加载
                    </el-button>
                    <el-button @click="submit" type="success" plain style="height:40px;width:35%;margin-left: 20px">
                        确定
                    </el-button>
                </el-col>
                <div id="chart" style="height: 400px;width: auto"></div>
                <div class="chartIcon">
                    <i class="fa fa-pie-chart fa-2x" aria-hidden="true" @click="toPie"></i>
                    <i class="fa fa-bar-chart fa-2x" aria-hidden="true" @click="toBar"></i>
                    <i class="fa fa-line-chart fa-2x" aria-hidden="true" @click="toLine"></i>
                    <i class="fa fa-align-left fa-2x" aria-hidden="true" @click="toSbar"></i>
                    <i class="fa fa-undo fa-2x" aria-hidden="true" @click="toGauge"></i>
                </div>
            </div>
        </el-dialog>
        <div>
            <v_areaDialog :areaVisible="areaVisible"></v_areaDialog>
        </div>
    </div>
</template>

<script>
    import echarts from 'echarts';
    import areaDialog from '../../components/dialog/areaDialog';

    export default {
        name: "chartDivDialog",
        data() {
            return {
                isLoad: false,
                isSelected: false,
                canSelected: false,
                time: '',
                paramsFormData: '',
                value: '',
                xfield: '',
                yfield: '',
                num: '',
                options: [],
                fieldOption: [],
                currentDiv: '',
                chartType: 'bar',
                chartData: [],
                divOption: {},
                openedDialogParams: [],
                areaVisible: {
                    v: false
                },
            }
        },
        components: {
            "v_areaDialog": areaDialog,
        },
        props: {
            chartDivDialogVisible: Object,
        },
        methods: {
            openPosition() {
                this.$Bus.$emit('areaVisible.v', true);
            },
            showTable() {
                this.$method.getOptionData("addNew", this.showTableCallback);
            },
            showTableCallback(res) {
                this.options = res;
            },
            showField() {
                if (this.value !== "") {
                    this.fieldOption = this.$method.getField(this.num, this.showFieldCallback);
                } else {
                    this.fieldOption = [];
                    this.xfield = '';
                    this.yfield = '';
                }
            },
            showFieldCallback(res, selected) {
                this.fieldOption = res;
                this.canSelected = selected;
            },
            changeDataFields(value) {
                this.num = value;
                this.isSelected = false;
                this.canSelected = false;
                this.fieldOption = [];
                this.xfield = '';
                this.yfield = '';
                this.showField();
            },
            chartInit(val, chartData, chartId) {
                let option = {};
                if (val === 'bar') {
                    option = this.$changeChart.toBarchartData(chartData);
                } else if (val === 'line') {
                    option = this.$changeChart.toLinechartData(chartData);
                } else if (val === 'pie') {
                    option = this.$changeChart.toPiechartData(chartData);
                } else if (val === 'Sbar') {
                    option = this.$changeChart.toBarbarChartData(chartData);
                    console.log(option)
                } else if (val === 'gauge') {
                    option = this.$changeChart.toGuageChartData(chartData);
                }
                // }
                const chartDivDialog = echarts.init(document.getElementById(chartId));
                //清空画布
                chartDivDialog.clear();
                chartDivDialog.setOption(option);
                window.addEventListener('resize', function () {
                    chartDivDialog.resize()
                });
                this.divOption = option;
            },
            load() {
                let that = this;
                if (this.isSelected == true) {
                    if (this.value == '气温') {
                        this.chartData = [{"time": 2, "tem": 0}, {"time": 4, "tem": 1}, {
                            "time": 6,
                            "tem": 3
                        }, {"time": 8, "tem": 4}, {"time": 10, "tem": 5}, {"time": 12, "tem": 8}, {
                            "time": 14,
                            "tem": 14
                        }, {"time": 16, "tem": 12}, {
                            "time": 18, "tem": 8
                        }, {"time": 20, "tem": 5}, {"time": 22, "tem": 3}, {"time": 24, "tem": 1}];
                    } else if (this.value == '空气质量指数') {
                        this.chartData = [
                            {"Time": "1", "AQI": "93"},
                            {"Time": "2", "AQI": "89"},
                            {"Time": "3", "AQI": "85"},
                            {"Time": "4", "AQI": "79"},
                            {"Time": "5", "AQI": "79"},
                            {"Time": "6", "AQI": "75"},
                            {"Time": "7", "AQI": "72"},
                            {"Time": "8", "AQI": "71"},
                            {"Time": "9", "AQI": "60"},
                            {"Time": "10", "AQI": "60"},
                            {"Time": "11", "AQI": "55"},
                            {"Time": "12", "AQI": "53"},
                            {"Time": "13", "AQI": "53"},
                            {"Time": "14", "AQI": "59"},
                            {"Time": "15", "AQI": "62"},
                            {"Time": "16", "AQI": "65"},
                            {"Time": "17", "AQI": "68"},
                            {"Time": "18", "AQI": "79"},
                            {"Time": "19", "AQI": "85"},
                            {"Time": "20", "AQI": "95"},
                            {"Time": "21", "AQI": "95"},
                            {"Time": "22", "AQI": "102"},
                            {"Time": "23", "AQI": "104"},
                            {"Time": "24", "AQI": "100"}];
                    } else if (this.value == '平均PM2.5') {
                        this.chartData = [
                            {"Time": "1", "pm": "230.1142857"},
                            {"Time": "2", "pm": "229.1142857"},
                            {"Time": "3", "pm": "221.8571429"},
                            {"Time": "4", "pm": "216.2285714"},
                            {"Time": "5", "pm": "215.9142857"},
                            {"Time": "6", "pm": "220.8571429"},
                            {"Time": "7", "pm": "214.0571429"},
                            {"Time": "8", "pm": "200.9428571"},
                            {"Time": "9", "pm": "198.1428571"},
                            {"Time": "10", "pm": "206"},
                            {"Time": "11", "pm": "218.5714286"},
                            {"Time": "12", "pm": "229.9428571"},
                            {"Time": "13", "pm": "246.1428571"},
                            {"Time": "14", "pm": "247.4"},
                            {"Time": "15", "pm": "254.2571429"},
                            {"Time": "16", "pm": "255.1428571"},
                            {"Time": "17", "pm": "251.2857143"},
                            {"Time": "18", "pm": "253.9142857"},
                            {"Time": "19", "pm": "263.1142857"},
                            {"Time": "20", "pm": "259.6"},
                            {"Time": "21", "pm": "268.2285714"},
                            {"Time": "22", "pm": "266.4285714"},
                            {"Time": "23", "pm": "265.3235294"},
                            {"Time": "24", "pm": "262.6285714"}];
                    } else if (this.value == '污染大气观测指数') {
                        this.chartData = [
                            {"kind": "PM10", "value": "100"},
                            {"kind": "PM2.5", "value": "75"},
                            {"kind": "NO2", "value": "23"},
                            {"kind": "SO2", "value": "13"},
                            {"kind": "O3", "value": "40"},
                            {"kind": "CO", "value": "8"}];
                    } else if (this.value == '空气相对湿度') {
                        this.chartData = [{"sName": "空气湿度", "description": "湿度", "value": "35", "unit": "%"}]
                    } else if (this.value == '天气常见参数') {
                        this.tableData = [
                            {"指标": "天气", "状态": "晴"},
                            {"指标": "气温", "状态": "0-14℃"},
                            {"指标": "风向", "状态": "西北风"},
                            {"指标": "风速", "状态": "<3级"},
                            {"指标": "湿度", "状态": "24%"},
                            {"指标": "气压", "状态": "1022hpa"}]
                    } else {
                        let queryUrl = "/parallel/result/preview/" + this.value + '?size=50000';
                        that.$axios.get(queryUrl).then(function (res) {
                            if (res.code == 200) {
                                console.log(res.body);
                                // that.chartInit(that.chartType, res.body);
                                that.chartData = res.body;
                            } else {
                                that.$message(res.message);
                            }
                        })
                    }
                } else if (this.isSelected == false) {
                    let statiData = {};
                    // statiData.tag=this.name;
                    statiData.dataId = this.value;
                    if (this.time != '') {
                        let start = this.time[0];
                        let end = this.time[1];
                        let star = new Date(start.toString().substring(4, 24));
                        let en = new Date(end.toString().substring(4, 24));
                        statiData.timeRange = star.getTime() + "," + en.getTime();
                    }
                    statiData.spatialFilter = this.paramsFormData;
                    // statiData.sql = this.inputAttr;
                    let xGroup = '';
                    for (let i = 0; i < this.fieldOption.length; i++) {
                        if (this.xfield == this.fieldOption[i].field) {
                            xGroup = this.fieldOption[i].fieldName;
                        }
                    }
                    statiData.groupField = xGroup;
                    let yGroup = '';
                    for (let i = 0; i < this.fieldOption.length; i++) {
                        if (this.yfield == this.fieldOption[i].field) {
                            yGroup = this.fieldOption[i].fieldName;
                        }
                    }
                    statiData.statField = yGroup;
                    console.log(statiData);
                    let currentApplicationID = {};
                    this.$axios.post('/parallel/data/stat/' + statiData.dataId, statiData
                    ).then(function (response) {
                        // console.log(response);
                        currentApplicationID = response.body;
                        console.log(currentApplicationID);
                        that.$message({
                            type: 'success',
                            message: '任务提交成功，正在加载'
                        });
                    }).catch(function (error) {
                        that.$message({
                            type: 'warning',
                            message: '任务提交失败'
                        });
                    });
                    let superviseTimer = setInterval(function () {
                        that.$axios.get('/parallel/monitor/' + currentApplicationID)
                            .then(function (response) {
                                if (response.body.finalStatus == "UNDEFINED") {
                                    that.isLoad = true;
                                }
                                // if (response.body.finalStatus !== "SUCCEEDED") {
                                //     that.isLoad = true;
                                // }
                                else if (response.body.finalStatus === "FAILED"
                                    || response.body.finalStatus === "KILLED") {
                                    clearInterval(superviseTimer);
                                    that.isLoad = false;
                                    that.$message({
                                        type: 'warning',
                                        message: '加载失败'
                                    });
                                }
                                else {
                                    clearInterval(superviseTimer);
                                    that.isLoad = false;
                                    let queryUrl = "/parallel/result/preview/" + currentApplicationID + '?size=50000';
                                    that.$axios.get(queryUrl).then(function (res) {
                                        if (res.code == 200) {
                                            // that.chartInit(that.chartType, res.body);
                                            console.log(res);
                                            that.chartData = res.body;
                                        } else {
                                            that.$message(res.message);
                                        }
                                    })
                                }
                            })
                    }, 5000);
                }
            },
            submit() {
                const chartDiv = echarts.init(document.getElementById(this.currentDiv.chartId));
                chartDiv.clear();
                chartDiv.setOption(this.divOption);
                chartDiv.resize();
                console.log($('#' + this.currentDiv.chartId).find('.chartDivTitle'));
                $('#' + this.currentDiv.id).find('.chartDivTitle').html(this.value);
                window.addEventListener('resize', function () {
                    chartDiv.resize()
                });
                document.getElementById(this.currentDiv.id).parentElement.onclick = function () {
                    chartDiv.resize();
                };
                const chartDivDialog = echarts.init(document.getElementById('chart'));
                chartDivDialog.clear();//清空画布
                this.chartDivDialogVisible.v = false;
                if (this.openedDialogParams.length === 0) {
                    this.openedDialogParams.push({
                        id: this.currentDiv.id,
                        fieldSelect: this.canSelected,
                        otherSelect: this.isSelected,
                        tableValue: this.value,
                        xField: this.xfield,
                        yField: this.yfield,
                        chartData: this.chartData,
                        chartType: this.chartType
                    });
                } else {
                    for (let openedDialogData of this.openedDialogParams) {
                        if (this.currentDiv.id !== openedDialogData.id) {
                            this.openedDialogParams.push({
                                id: this.currentDiv.id,
                                fieldSelect: this.canSelected,
                                otherSelect: this.isSelected,
                                tableValue: this.value,
                                xField: this.xfield,
                                yField: this.yfield,
                                chartData: this.chartData,
                                chartType: this.chartType
                            });
                        } else {
                            openedDialogData.fieldSelect = this.canSelected;
                            openedDialogData.otherSelect = this.isSelected;
                            openedDialogData.tableValue = this.value;
                            openedDialogData.xField = this.xfield;
                            openedDialogData.yfield = this.yfield;
                            openedDialogData.chartData = this.chartData;
                            openedDialogData.chartType = this.chartType;
                        }
                    }
                }

            },

            toBar() {
                this.chartType = 'bar';
            },
            toPie() {
                this.chartType = 'pie';
            },
            toLine() {
                this.chartType = 'line';
            },
            toSbar() {
                this.chartType = 'Sbar';
            },
            toGauge() {
                this.chartType = 'gauge';
            }
        },
        created() {
            this.isLoad = false;
            let that = this;
            this.$Bus.$on('chartDivDialogVisible.v', (e) => {
                that.chartDivDialogVisible.v = e;
            });
            this.$Bus.$on('currentChartDiv', (currentChart) => {
                that.currentDiv = currentChart;
                for (let openedDialog of that.openedDialogParams) {
                    if (that.currentDiv.id == openedDialog.id) {
                        that.value = openedDialog.tableValue;
                        that.xfield = openedDialog.xField;
                        that.yfield = openedDialog.yField;
                        that.canSelected = openedDialog.fieldSelect;
                        that.isSelected = openedDialog.otherSelect;
                        that.chartData = openedDialog.chartData;
                        that.chartType = openedDialog.chartType;
                        that.chartInit(that.chartType, that.chartData, "chart");
                        break;
                    } else {
                        this.value = '';
                        this.xfield = '';
                        this.yfield = '';
                        this.canSelected = false;
                        this.isSelected = false;
                        this.chartData = [];
                        this.chartType = 'bar';
                    }
                }
            });

        },
        mounted() {
            this.showTable();
            let that = this;
            this.$Bus.$on('coordinate', (params) => {
                // console.log(params);
                that.paramsFormData = params;
            });

        },
        watch: {
            chartType(newVal, oldVal) {
                console.log(newVal, oldVal);
                this.chartType = newVal;
                this.chartInit(newVal, this.chartData, "chart");
            },
            chartData(newValue, oldValue) {
                // this.chartData = newValue;
                if (this.chartData.length !== 0) {
                    this.chartInit(this.chartType, newValue, "chart");
                }
            },
            value(newVal, oldVal) {
                if (newVal == '气温') {
                    this.isSelected = true;
                } else if (newVal == '空气质量指数') {
                    this.isSelected = true;
                } else if (newVal == '平均PM2.5') {
                    this.isSelected = true;
                } else if (newVal == '污染大气观测指数') {
                    this.isSelected = true;
                } else if (newVal == '空气相对湿度') {
                    this.isSelected = true;
                } else if (newVal == '天气常见参数') {
                    this.isSelected = true;
                }
            },
            // chartData(newValue,oldValue) {
            //     if(newValue !==[]){
            //
            //     }
            // }
        }
    }
</script>

<style>
    .el-loading-mask {
        /*margin-top: 15vh;*/
        /*width: 64%;*/
        /*height: 600px;*/
        /*margin-left: 69vh*/
        z-index: 1000;
    }

    .chartIcon i {
        margin: 10px;
        /*border: 1px solid #ddd;*/
        padding: 6px 8px;
        font-size: 24px;
        text-align: left;
        color: #3a8ee6;
    }

    .chartIcon i:hover {
        color: #ddd;
    }

    .chartIcon {
        width: 50px;
        margin-top: 20px;
    }

    #chart {
        flex: 1;
    }

    .content {
        width: auto;
        display: flex;
    }
</style>